//
//  BaseTabBarController.swift
//  demo3
//
//  Created by zaizai on 2018/5/31.
//  Copyright © 2018年 guest. All rights reserved.
//

import UIKit

class BaseTabBarController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let tabbar = UITabBar.appearance()
        
        tabbar.tintColor = UIColor.red
        tabbar.barTintColor = UIColor.white
        /// 添加子控制器
        addChildViewControllers()
    }
    
    /// 设置控制器
    private func setChildController(controller: UIViewController, imageName: String) {

        controller.tabBarItem.image = UIImage(named: imageName + "nor")?.withRenderingMode(.alwaysOriginal)
        controller.tabBarItem.selectedImage = UIImage(named: imageName + "selected")?.withRenderingMode(.alwaysOriginal)
    }
    /// 添加子控制器
    private func addChildViewControllers() {
        
        setChildViewController(ShouYeviewcontroller(), title: "首页", imageName: "shouye_")
        setChildViewController(FenLeiviewcontroller(), title: "分类", imageName: "fenlei_")
        setChildViewController(XAFoundViewController(), title: "发现", imageName: "discover_")
        setChildViewController(WoDeviewcontroller(), title: "我的", imageName: "wode_")
    }
    /// 初始化子控制器
    private func setChildViewController(_ childController: UIViewController, title: String, imageName: String) {
        // 设置 tabbar 文字和图片
        setChildController(controller: childController, imageName: imageName)
        childController.title = title
        // 添加导航控制器为 TabBarController 的子控制器
        addChild(BaseNavigationController(rootViewController: childController))
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
//自定义tabbar解决iPhoneX modal并返回之后， 再push后，tabBar偏移问题
class YKTabBar: UITabBar {
    
    var oldSafeAreaInsets = UIEdgeInsets.zero
    
    @available(iOS 11.0, *)
    override func safeAreaInsetsDidChange() {
        super.safeAreaInsetsDidChange()
        
        if oldSafeAreaInsets != safeAreaInsets {
            oldSafeAreaInsets = safeAreaInsets
            
            invalidateIntrinsicContentSize()
            superview?.setNeedsLayout()
            superview?.layoutSubviews()
        }
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        var size = super.sizeThatFits(size)
        if #available(iOS 11.0, *) {
            let bottomInset = safeAreaInsets.bottom
            if bottomInset > 0 && size.height < 50 && (size.height + bottomInset < 90) {
                size.height += bottomInset
            }
        }
        return size
    }
    
    override var frame: CGRect {
        get {
            return super.frame
        }
        set {
            var tmp = newValue
            if let superview = superview, tmp.maxY !=
                superview.frame.height {
                tmp.origin.y = superview.frame.height - tmp.height
            }
            
            super.frame = tmp
        }
    }
}
